package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.service.IService;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BusinessException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private IService<DishFlavor> dishFlavorService;

    @Override
    public IPage<Dish> pageDish(IPage<Dish> page, DishPageQueryDTO dishPageQueryDTO) {
        log.info("菜品分页查询，参数：{}，页码：{}，每页条数：{}",
                dishPageQueryDTO, page.getCurrent(), page.getSize());
        return dishMapper.pageDish(page, dishPageQueryDTO);
    }

    /**
     * 新增菜品
     */
    @Override
    @Transactional
    public void saveDish(DishDTO dishDTO) {
        // 参数校验
        validateDishDTO(dishDTO, true);

        log.info("开始新增菜品，菜品信息：{}", dishDTO);

        // 转换DTO为实体
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        // 保存菜品基本信息
        this.save(dish);
        Long dishId = dish.getId();
        log.info("菜品基础信息保存成功，生成ID：{}", dishId);

        // 处理口味信息
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (!CollectionUtils.isEmpty(flavors)) {
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            // 使用MyBatis-Plus的IService批量插入
            dishFlavorService.saveBatch(flavors);
            log.info("菜品口味信息保存成功，共{}条", flavors.size());
        }
    }

    /**
     * 修改菜品
     */
    @Override
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        // 参数校验
        validateDishDTO(dishDTO, false);

        log.info("开始修改菜品，菜品ID：{}，修改信息：{}", dishDTO.getId(), dishDTO);

        // 转换DTO为实体
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        // 更新菜品基本信息
        this.updateById(dish);
        log.info("菜品基础信息更新成功");

        // 处理口味数据
        handleDishFlavors(dish.getId(),dishDTO.getFlavors());
    }

    @Override
    public List<DishVO> listDishByCategoryId(Long categoryId) {
        List<DishVO>list=dishMapper .listDishByCategoryId(categoryId);
        return list;
    }

    /**
     * 处理菜品口味（删除旧口味 + 插入新口味）
     */
    private void handleDishFlavors(Long dishId, List<DishFlavor> flavors) {
        log.info("开始处理菜品[ID:{}]的口味信息", dishId);

        // 删除旧口味
        LambdaUpdateWrapper<DishFlavor> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(DishFlavor::getDishId, dishId);
        int deleteCount = dishFlavorMapper.delete(updateWrapper);
        log.info("删除菜品旧口味{}条", deleteCount);

        // 插入新口味
        if (!CollectionUtils.isEmpty(flavors)) {
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            // 使用MyBatis-Plus的IService批量插入
            dishFlavorService.saveBatch(flavors);
            log.info("插入菜品新口味{}条", flavors.size());
        }
    }

    /**
     * 校验菜品DTO参数
     * @param dishDTO 菜品DTO
     * @param isNew 是否为新增操作
     */
    private void validateDishDTO(DishDTO dishDTO, boolean isNew) {
        if (dishDTO == null) {
            throw new BusinessException("菜品参数不能为空");
        }

        // 新增时无需校验ID，修改时必须校验ID
        if (!isNew && dishDTO.getId() == null) {
            throw new BusinessException("菜品ID不能为空");
        }

        // 校验关键业务字段
        if (dishDTO.getName() == null || dishDTO.getName().trim().isEmpty()) {
            throw new BusinessException("菜品名称不能为空");
        }
        if (dishDTO.getCategoryId() == null) {
            throw new BusinessException("菜品分类ID不能为空");
        }
        if (dishDTO.getPrice() == null || dishDTO.getPrice().compareTo(BigDecimal.ZERO) < 0) {
            throw new BusinessException("菜品价格必须大于等于0");
        }
    }
}
